/*
 * @Author: LiZhiWei
 * @Date: 2025-07-15 10:19:07
 * @LastEditors: wjc
 * @LastEditTime: 2025-10-29 17:53:25
 * @Description: 统一的创建功能Hook，支持弹窗创建和嵌入式创建
 */
import { api, Http } from '#/api'
import Validation from '#/utils/validation'
import { ElMessage } from 'element-plus'

export function useCreator(
  options: {
    entity?: string
    formSize?: 'large' | 'mini' | 'normal' | string
    message?: string
    mode?: 'embed' | BaseFormMode
  } = {
    mode: 'dialog',
    formSize: 'normal',
    entity: '',
    message: '添加成功',
  }
) {
  const { entity = '', message, formSize } = options
  // 通用状态
  const loading = ref(false)
  const formLoading = ref(false)
  // 创建对话框或抽屉
  const createDialog = ref({
    visible: false,
    entity,
    size: formSize,
  })

  // 表单控件
  const createFormer = ref({
    fields: [],
    data: {},
    validate: new Validation(),
  })

  const create = (url: string, params: any) => {
    if (loading.value) return Promise.reject(new Error('操作进行中'))
    loading.value = true

    return Http.Get(url, { params })
      .then((res) => {
        return res
      })
      .finally(() => {
        loading.value = false
      })
  }

  const afterCreated = (res: any, onCreated?: (res: any) => void) => {
    createFormer.value.fields = res.data
    onCreated && onCreated(res)
  }

  // 获取表单配置
  const getCreateForm = (onCreated?: (res: any) => void) => {
    create(api[entity].create, {}).then((res) => {
      afterCreated(res, onCreated)
    })
  }

  const getCreateFormWith = (url: RequestUrl, onCreated?: (res: any) => void) => {
    create(url.create as string, url.params).then((res) => {
      afterCreated(res, onCreated)
    })
  }

  const store = (url: string, data: any) => {
    if (formLoading.value) return Promise.reject(new Error('操作进行中'))
    formLoading.value = true

    return Http.Post(url, data)
      .then((res) => {
        ElMessage({ message: message ?? '添加成功', type: 'success' })
        createFormer.value.validate.clean()
        return res
      })
      .catch((error) => {
        createFormer.value.validate.setMessages(error?.response?.data?.errors)
      })
      .finally(() => {
        formLoading.value = false
      })
  }

  const afterStored = (res: any, onStored?: (res: any) => void) => {
    onStored && onStored(res)
  }

  // 表单提交
  const handleStore = (data: object, onConfirmed?: (res: any) => void) => {
    store(api[entity].store, data).then((res) => {
      afterStored(res, onConfirmed)
    })
  }

  const handleStoreWith = (url: RequestUrl, onConfirmed?: (res: any) => void) => {
    store(url.store as string, url.params).then((res) => {
      afterStored(res, onConfirmed)
    })
  }

  // dialog, drawer 创建
  const showCreator = () => {
    createFormer.value.data = {}
    createDialog.value.visible = true
  }

  const resetCreator = () => {
    formLoading.value = false
    createFormer.value?.validate.clean()
  }

  // 页面路由
  const getReturnRoute = (routeName?: string) => {
    return routeName || `${entity}Index`
  }

  return {
    loading,
    formLoading,
    createDialog,
    createFormer,
    showCreator,
    resetCreator,
    getCreateForm,
    getCreateFormWith,
    handleStore,
    handleStoreWith,
    getReturnRoute,
  }
}
